package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/*
 *  @author 雨安
 *  类名： SecurityConfig
 *  创建时间：2024/3/13
 */
@Configuration
@EnableWebSecurity // 开启Security服务
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 使用userDetailsService来加载用户信息,并给用户的密码进行加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    /**
     * 默认没有,手动调用,密码加密接口PasswordEncoder
     */
    @Bean
    PasswordEncoder password(){
        //返回加密对象
        return new BCryptPasswordEncoder();
    }

    //配置权限


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //配置登录列表
            .formLogin()
            .loginPage("/login.html") //设置自定义登录界面
            .loginProcessingUrl("/user/login") //设置登录列表的提交路径
            .defaultSuccessUrl("/test/index").permitAll() //配置登录成功路径
            .and()
                //配置请求的权限
            .authorizeHttpRequests()
                .antMatchers("/","/test/hello").permitAll()//所有都可以访问
                //当前登录用户，只有具有admins权限才可以访问这个路径“/test/index”
                .antMatchers("/test/haha").hasAuthority("admin")
                .anyRequest().authenticated() //其他请求需要进行身份验证
                .and()
                //关闭CSRF保护
        .csrf().disable();
    }
}
